<?php

namespace app\modules\api\controllers;

use app\models\ApiClient;
use app\models\ApiException;
use app\models\ApiVersion;
use Yii;

/**
 * API控制器基类
 * Class BaseController
 * @package app\modules\api\controllers
 */
class BaseController extends BasePublicController
{
    /**
     * @var string 客户端使用的接口版本号
     */
    protected $client_api_version = '';
    /**
     * @var string 客户端使用的AppId
     */
    protected $app_id = '';

    /**
     * @inheritdoc
     * @throws ApiException
     */
    public function beforeAction($action)
    {
        if (!Yii::$app->request->isOptions) {
            if (!$this->checkVersion(Yii::$app->request->get('version'))) {
                return false;
            }
            if (!$this->checkSign()) {
                return false;
            }
        }
        return parent::beforeAction($action);
    }

    /**
     * 检查版本
     * @param string $version 客户端使用的接口版本
     * @return boolean
     * @throws ApiException
     */
    private function checkVersion($version)
    {
        if (empty($version)) {
            throw new ApiException('PARAM', '没有找到接口版本号参数。');
        }
        $apiVersion = ApiVersion::findOne(['version' => $version]);
        if (empty($apiVersion)) {
            throw new ApiException('VERSION', '版本号错误，没有找到此版本信息。');
        }
        if ($apiVersion->is_support != 1) {
            /** @var ApiVersion $version */
            $version = ApiVersion::find()->orderBy('create_time DESC')->one();
            if (empty($version)) {
                throw new ApiException('VERSION', '系统没有定义版本号信息。');
            }
            throw new ApiException('VERSION_UPDATE', '版本不兼容，请更新接口。', [], [
                'version' => $version->version,
                'update_info' => $version->update_info,
            ]);
        }
        $this->client_api_version = $version;
        return true;
    }

    /**
     * 鉴权
     * @return true
     * @throws ApiException
     */
    private function checkSign()
    {
        $appId = Yii::$app->request->get('app_id');
        if (empty($appId)) {
            throw new ApiException('PARAM', '没有找到AppId参数。');
        }
        $apiClient = ApiClient::findByAppId($appId);
        if (empty($apiClient)) {
            throw new ApiException('APP_ID', '没有找到接口授权。');
        }
        if ($apiClient->status != ApiClient::STATUS_ACTIVE) {
            throw new ApiException('APP_ID', '接口授权异常。');
        }
        $this->app_id = $appId;
        if (YII_ENV !== 'prod' && Yii::$app->request->get('debug') == 1) {
            return true;
        }
        return $apiClient->checkSign($this->get());
    }
}
